package com.samphanie.security.validation.service;

import cn.hutool.core.util.StrUtil;
import com.samphanie.common.service.IRedisService;
import com.samphanie.security.domain.Captcha;
import com.samphanie.security.validation.enums.ValidateCodeType;
import com.samphanie.security.validation.exception.ValidateCodeException;
import com.samphanie.security.validation.properties.ValidateProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.ServletWebRequest;

import javax.annotation.Resource;

/**
 * @author ZSY
 * @email 1451691457@qq.com
 */
@Slf4j
public class RedisValidateCodeServiceImpl implements ValidateCodeMapper {

    @Resource
    private ValidateProperties validateProperties;
    @Resource
    private IRedisService redisService;

    /***
     * save 保存验证码
     **/
    @Override
    public void save(ServletWebRequest request, Captcha captcha, ValidateCodeType validateCodeType) {
        long expireIn = 60;
        if (validateCodeType.equals(ValidateCodeType.IMAGE)) {
            expireIn = validateProperties.getKaptcha().getExpireIn();
        } else {
            expireIn = validateProperties.getSms().getExpireIn();
        }

        redisService.set(buildKey(request, validateCodeType), captcha, expireIn);
    }

    /***
     * get 获取验证码
     **/
    @Override
    public Captcha get(ServletWebRequest request, ValidateCodeType validateCodeType) {
        Object value = redisService.get(buildKey(request, validateCodeType));
        if (value == null) {
            return null;
        }

        return (Captcha) value;
    }

    /***
     * remove 移除验证码
     **/
    @Override
    public void remove(ServletWebRequest request, ValidateCodeType validateCodeType) {
        redisService.del(buildKey(request, validateCodeType));
    }

    private String buildKey(ServletWebRequest request, ValidateCodeType codeType) {

        String deviceId = request.getHeader("deviceId");
        if (StrUtil.isBlank(deviceId)) {
            throw new ValidateCodeException("请在请求头中携带deviceId参数");
        }

        return "code:" + codeType.toString().toLowerCase() + ":" + deviceId;
    }

}
